#两两交换链表中的节点
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy

        while pre.next and pre.next.next:
            cur = pre.next
            next_node = cur.next
            temp = next_node.next

            # 交换当前两个节点
            pre.next = next_node
            next_node.next = cur
            cur.next = temp

            # 移动pre到当前对的第二个节点（即原来的第一个节点）
            pre = cur

        return dummy.next


def list_to_linkedlist(lst):
    """将列表转换为链表"""
    dummy = ListNode(0)
    current = dummy
    for num in lst:
        current.next = ListNode(num)
        current = current.next
    return dummy.next


def linkedlist_to_list(head):
    """将链表转换为列表"""
    res = []
    while head:
        res.append(head.val)
        head = head.next
    return res


if __name__ == "__main__":
    solution = Solution()

    # 测试用例
    test_cases = [
        [1, 2, 3, 4],  # 示例1
        [],  # 示例2
        [1],  # 示例3
    ]

    for case in test_cases:
        # 构建链表
        head = list_to_linkedlist(case)
        # 交换节点
        new_head = solution.swapPairs(head)
        # 转换回列表
        result = linkedlist_to_list(new_head)
        # 打印结果
        print(f"输入: {case} -> 输出: {result}")